package top.iszsq.config.advice;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.iszsq.base.entity.Render;
import top.iszsq.base.utils.RenderUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 自定义错误返回
 * @author zsq
 * @date 2021/5/18 15:41
 **/
@Controller
public class CustomErrorController extends AbstractErrorController {

    private static final Logger logger = LoggerFactory.getLogger(CustomErrorController.class);

    public CustomErrorController(ErrorAttributes errorAttributes) {
        super(errorAttributes);
    }

    @Override
    public String getErrorPath() {
        return "/error";
    }

    /**
     * 请求错误，404 401 等
     * @return
     */
//    @RequestMapping(value = "/error", produces = MediaType.APPLICATION_JSON_VALUE)
    @RequestMapping(value = "/error")
    @ResponseBody
    public Render error(HttpServletRequest request, HttpServletResponse response) {
        Map body = this.getErrorAttributes(request, this.getTraceParameter(request));
        logger.debug("请求错误，错误数据：" + body);
        logger.debug("请求错误：" + response.getStatus());

        String path = body.get("path") != null ? body.get("path").toString() : "";

        return RenderUtils.fail("请求错误：" + response.getStatus() + "，路径：" + path, body);
    }

}
